/**
 * v-debounce
 * 按钮防抖指令，可扩展至input
 * 接收参数：
 *   1. function: 必传，防抖回调函数
 *   2. number: 可选，防抖时间（毫秒），默认500
 * 使用示例：
 *   <button v-debounce="handleClick">提交</button>
 *   <button v-debounce:[1000]="handleClick">提交</button>
 */
import type { Directive, DirectiveBinding } from 'vue';

interface ElType extends HTMLElement {
  __handleClick__: () => void;
  __debounceTime__: number;
}

const debounce: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    if (typeof binding.value !== 'function') {
      throw 'v-debounce: 回调必须是一个函数';
    }

    // 获取防抖时间（支持动态参数）
    const debounceTime = binding.arg ? parseInt(binding.arg) : 500;
    el.__debounceTime__ = debounceTime;

    let timer: NodeJS.Timeout | null = null;
    el.__handleClick__ = function () {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        binding.value();
      }, el.__debounceTime__);
    };

    el.addEventListener('click', el.__handleClick__);
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener('click', el.__handleClick__);
  }
};

export default debounce;
